package com.yxjx.duoxue.payment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import com.yxjx.duoxue.R;
import com.yxjx.duoxue.course.CourseOrderKidsOption;
import com.yxjx.duoxue.customview.YxListView;
import com.yxjx.duoxue.customview.YxRadioGroup;
import com.yxjx.duoxue.dao.Dao;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.payment.datamodel.DMKidInfoRefObject;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class OrderKidsConfigurationView extends LinearLayout implements OnClickListener {

	private View mRootView;
	private YxListView mListView;
	private ArrayList<ConfigKidsDetailDTS> data;
	private ArrayList<Boolean> selectedStates;
	private MyAdapter adapter;
	private Context mContext;
	private TextView childBirthText;
	// 出生年月
	private int selectedMonth = -1;
	private int selectedYear = -1;
	
	public int getSelectedMonth() {
		return selectedMonth;
	}

	public void setSelectedMonth(int selectedMonth) {
		this.selectedMonth = selectedMonth;
	}

	public int getSelectedYear() {
		return selectedYear;
	}

	public void setSelectedYear(int selectedYear) {
		this.selectedYear = selectedYear;
	}

	private DMKidInfoRefObject kidInfoTotal;

	public DMKidInfoRefObject getKidInfoTotal() {
		return kidInfoTotal;
	}

	public void setKidInfoTotal(DMKidInfoRefObject kidInfoTotal) {
		this.kidInfoTotal = kidInfoTotal;
		updateUIInternal(from(kidInfoTotal));
	}
	
	private ClientUserKidsDTS from(DMKidInfoRefObject kidInfo) {
		if (kidInfo == null) {
			return null;
		}
		ClientUserKidsDTS item = new ClientUserKidsDTS();
		item.setKidsName(kidInfo.getChildName());
		item.setKidsSex(kidInfo.getChildSex());
		item.setKidsBirthMonth(kidInfo.getKidBIrthMonth());
		item.setKidsBirthYear(kidInfo.getKidBirthYear());
		item.setCourseType(getCourseTypeIdString(kidInfo));
		item.setKidsDetail(getLabelIdString(kidInfo));
		return item;
	}

	private String getLabelIdString(DMKidInfoRefObject kidInfo) {
		if (kidInfo == null) {
			return "";
		}
		return KidInfoEditActivity.getLabelIdString(kidInfo.getSelectedLabels());
	}

	private String getCourseTypeIdString(DMKidInfoRefObject kidInfo) {
		if (kidInfo == null) {
			return "";
		}
		return KidInfoEditActivity.getCourseTypeIdString(kidInfo.getSelectedCourseTypes());
	}

	public OrderKidsConfigurationView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		mRootView = LayoutInflater.from(context).inflate(R.layout.segment_order_kids_configuration, this, true);
		
		childBirthText = (TextView) mRootView.findViewById(R.id.child_birth);
		UIHelper.setClickListener(mRootView, R.id.edit_kid_info, this);
		UIHelper.setClickListener(mRootView, R.id.child_birth, this);
	}

	private void setDataFromAppDataModel() {
		Globals appData = Globals.getInstance(getContext());
		if (appData.getKidOption() == null) {
			data = null;
		} else {
			if (appData.getKidOption().getKidsConfigList() != null) {
				data = (ArrayList<ConfigKidsDetailDTS>) appData.getKidOption().getKidsConfigList();
				// 初始化selectedStates
				selectedStates = new ArrayList<Boolean>(data.size());
				for (int i = 0; i < data.size(); i++) {
					selectedStates.add(false);
				}
			}
			
			ClientUserKidsDTS item = Dao.getUserKidInfo(mContext);
			updateUIInternal(item);
		}
	}

	private void updateUIInternal(ClientUserKidsDTS item) {
		updateBasicInfo(item);
	}

	private void updateBasicInfo(ClientUserKidsDTS item) {
		findViewById(R.id.edit_kid_info).setVisibility(
				item == null ? View.VISIBLE : View.GONE);
		
		if (item != null) {
			((TextView) findViewById(R.id.child_name)).setText(item.getKidsName());
			YxRadioGroup childSexView = (YxRadioGroup) findViewById(R.id.child_sex);
			childSexView.setSelectedIndex(item.getKidsSex());
			selectedYear = item.getKidsBirthYear();
			selectedMonth = item.getKidsBirthMonth();
			if (isValidBirthDay()) {
				String birthText = "" + selectedYear + "-" + selectedMonth;
				UIHelper.setText(mRootView, R.id.child_birth, birthText);
			}
		}
	}
	
	/**
	 * update kidinfo by UserLoginResponse kidInfo.
	 */
	public void updateByLoginInfo() {
		ClientUserKidsDTS kidInfo = Dao.getUserKidInfo(mContext);
		if (kidInfo != null) {
			updateBasicInfo(kidInfo);
		}
	}

	public static ArrayList<Integer> str2IntegerArray(String str) {
		if (UIHelper.isEmpty(str)) {
			return new ArrayList<Integer>();
		}
		
		String[] strs = str.trim().split(",");
		ArrayList<Integer> ret = new ArrayList<Integer>();
		for (String item : strs) {
			try {
				int intValue = Integer.valueOf(item);
				ret.add(intValue);
			} catch (Exception e) {
				//
			}
		}
		return ret;
		
	}
	
	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			int len = data == null ? 0 : data.size();
			return len;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(mRootView.getContext()).inflate(R.layout.item_kid_config_list, null);
			} else {
				ret = arg1;
			}
			UIHelper.setText(ret, R.id.text, data.get(arg0).getKidsDes());
			ret.findViewById(R.id.text).setSelected(selectedStates.get(arg0));
			ret.findViewById(R.id.indicator).setSelected(selectedStates.get(arg0));
			
			return ret;
		}
	}
	
	/**
	 * 更新VIew中的列表项，如果isShowCode == false, 则隐藏自己。
	 */
	public void update() {
		CourseOrderKidsOption option = Globals.getInstance(getContext()).getKidOption();
		if (option != null && option.isShowCode()) {
			setDataFromAppDataModel();
		}
	}
	
	/**
	 * 获取selected num
	 * @return
	 */
	public int getSelectedNum() {
		if (selectedStates == null || data == null) {
			return -1;
		} else if (selectedStates.size() != data.size()) {
			return -1;
		} else {
			int ret = 0;
			for (int i = 0; i < data.size(); i++) {
				if (selectedStates.get(i)) {
					ret++;
				}
			}
			return ret;
		}
	}
	
	/**
	 * 获取selectedIdsString
	 * @return
	 */
	public String getSelectedLablesId() {
		if (selectedStates == null || data == null) {
			return "";
		} else if (selectedStates.size() != data.size()) {
			return "";
		} else {
			String ret = "";
			for (int i = 0; i < data.size(); i++) {
				if (selectedStates.get(i)) {
					ret += ("" + data.get(i).getId() + ",");
				}
			}
			if (ret.length() > 0) {
				return ret.substring(0, ret.length() - 1);
			}
			return "";
		}
	}
	
	
	public static void pickDate(Context context, int initYear, int initMonth, final OnDateChangedListener listener) {
		Utils.logd("show calendar");
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		View dlgView = View.inflate(context, R.layout.segment_dlg_date_picker, null);
		final DatePicker datePicker = (DatePicker) dlgView.findViewById(R.id.date_picker);
		builder.setView(dlgView);
		builder.setTitle("选择出生年月");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				if (listener != null) {
					listener.onDateChanged(datePicker, datePicker.getYear(), datePicker.getMonth(), 1);
				}
				arg0.dismiss();
			}
		});
		int useYear = initYear;
		int useMonth = initMonth;
		if (useYear <= 0 || useMonth <= 0) {
			useYear = 2010;
			useMonth = 1;
		}
        datePicker.init(useYear, useMonth - 1, 1, null); 
        customizeHidePicker(datePicker);
        builder.show();
	}
	
    /**
     * 隐藏或者显示相应的时间项
     * 
     * @param picker 传入一个DatePicker对象
     */
	private static void customizeHidePicker(DatePicker picker) {
		// 利用java反射技术得到picker内部的属性，并对其进行操作
		Class<? extends DatePicker> c = picker.getClass();
		try {
			// 为了简单，缩写了... fd是field_day,fm是field_month。
			Field fd = null, fm = null;
			// 在这里做判断，入过系统版本大于4.0，就让他执行这一块,不做判断在有的手机可能没法实现
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
				fd = c.getDeclaredField("mDaySpinner");
				fm = c.getDeclaredField("mMonthSpinner");
			} else {
				fd = c.getDeclaredField("mDayPicker");
				fm = c.getDeclaredField("mMonthPicker");
			}
			// 对字段获取设置权限
			fd.setAccessible(true);
			fm.setAccessible(true);
			// 得到对应的控件
			View vd = (View) fd.get(picker);
			View vm = (View) fm.get(picker);
			// Type是3表示显示年月，隐藏日,vd可以从下面提取出来的，懒的 ...o(╯□╰)o
			int queryType = 3;
			if (queryType == 3) {
				vd.setVisibility(View.GONE);
				vm.setVisibility(View.VISIBLE);
			}// Type是4代表显示年，隐藏日和月
			else if (queryType == 4) {
				vd.setVisibility(View.GONE);
				vm.setVisibility(View.GONE);
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		hideDay(picker);
	}
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB) 
	private static void hideDay(DatePicker datePicker) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			datePicker.setCalendarViewShown(false);
		}
	}
	
	private void editKidInfo() {
		if (mContext instanceof OrderSubmitActivity) {
			((OrderSubmitActivity) mContext).editKidInfo();
		}
	}
	
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.edit_kid_info:
			editKidInfo();			
			break;
		case R.id.child_birth:
			pickDate(mContext, selectedYear, selectedMonth, new OnDateChangedListener() {
				
				@Override
				public void onDateChanged(DatePicker picker, int year, int month, int day) {
					if (!isValidBirthDay(month, year)) {
						UIHelper.showTips(mRootView, "请选择有效的年月");
						return;
					}
					selectedYear = year;
					selectedMonth = month + 1;
					setBirthText(selectedYear, selectedMonth);
					
				}
			});
			break;
		default:
			break;
		}

	}
	
	private boolean isValidBirthDay(int month, int year) {
		Calendar cal = Calendar.getInstance();
		int nowMonthCount = cal.get(Calendar.YEAR) * 12 + cal.get(Calendar.MONTH);
		int selectedMonthCount = month + year * 12;
		return selectedMonthCount <= nowMonthCount;
	}
	
	private void setBirthText(int year, int month) {
		if (year < 0 || month < 0) {
			childBirthText.setText("－");
			return;
		}
		String birthText = "" + year + "-" + (month);
		childBirthText.setText(birthText);
	}
	
	public boolean isValidBirthDay() {
		return selectedMonth >= 1
				&& selectedMonth <= 12
				&& selectedYear >= 1900
				&& isValidBirthDay(selectedYear, selectedMonth);
	}
}
